package com.tracesystem.commons;


import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Component
//@Aspect
public class RuleValidateAspect {

	private AntPathMatcher antPathMatcher = new AntPathMatcher();
	
	@Before("@annotation(com.tracesystem.commons.annotation.RuleValidate)")
	public void validateRule() {
		//权限认证
		//获取当前请求的uri
		HttpServletRequest request =((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
		String uri = request.getRequestURI();
		//获取用户的uri
        List<String> resoruces = (List<String>) request.getSession().getAttribute("login_uri_resource");
        System.out.println(uri + ":::" + resoruces);

        if (null == resoruces) {
            throw new AccessDeniedException("该角色没有权限");
        }
		boolean b = false;
		for(String ruri : resoruces) {
			if(antPathMatcher.match(ruri, uri)) {
				b = true;
				break;
			}
		}
		if(!b) throw new AccessDeniedException("未授权");
		
	}
	
}